package com.wxx.interceptior;

import cn.hutool.core.util.StrUtil;
import com.wxx.common.Const;
import com.wxx.model.DicUser;
import com.wxx.util.CookieUtil;
import com.wxx.util.JsonUtil;
import com.wxx.util.RedisPoolUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptior implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = CookieUtil.readLoginToken(request);
        //判断logintoken是否为空或者""；
        //如果不为空的话，符合条件，继续拿user信息
        if (StrUtil.isNotBlank(sessionId)){
            //查询redis中有没有存储用户信息
            String userJson = RedisPoolUtil.get(sessionId);
            DicUser user = JsonUtil.string2Obj(userJson,DicUser.class);
            if(user != null){
                //如果user不为空，则重置session的时间，即调用expire命令
                RedisPoolUtil.expire(sessionId, Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
                System.out.println("session验证通过");
                return true;
            }else{
                System.out.println("session失效");
                /*跳转到session过期页面*/
                response.sendRedirect("/jump/no_session");
                return false;
            }
        }else{
            System.out.println("session失效");
            /*跳转到session过期页面*/
            response.sendRedirect("/jump/no_session");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
